<?php
/**
 * Created by Moonpie Studio
 * User: Administrator
 * Date: 2017/9/26
 * Time: 14:55
 */

namespace Moonpie\Plugin\Enhancer\Service\View\Driver;


use app\common\service\App;
use think\exception\TemplateNotFoundException;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Loader\FilesystemLoader;

class TwigEngine implements EngineInterface
{
    /**
     * @var Environment
     */
    protected $environment;
    protected $config = [];

    public function __construct(Environment $environment, $config = array())
    {
        $this->config = array_merge($this->config, $config);
        $this->environment = $environment;
    }

    public function config($name, $value = null)
    {
        if (is_array($name)) {
            $this->config = array_merge($this->config, $name);
        } elseif (is_null($value)) {
            return isset($this->config[$name]) ? $this->config[$name] : null;
        } else {
            $this->config[$name] = $value;
        }
    }

    public function fetch($template, $vars, $configs)
    {
        try {

            return $this->parseTemplate($template, $vars, $configs);
        } catch (LoaderError $e) {
            throw new TemplateNotFoundException($e->getMessage(), $template);
        }
    }

    private function parseTemplate($template, $vars, $configs)
    {
        if (strpos($template, '@') > 0) {
            list($module, $subTmpl) = explode('@', $template);
            //$this->environment->getLoader()->prependPath(APP_PATH . $module . DS . 'view' . DS, $module);
            $template = "@{$module}/{$subTmpl}.twig";
        }else if(empty($template)){
            $request = request();
            $suffix = $request->isAjax() ? 'json' : 'html';
            $controller = strtolower($request->controller());
            $action = strtolower($request->action());
            $template = "{$controller}/{$action}.{$suffix}.twig";
        }else{
            $template .= '.twig';
        }
        echo strtr($this->environment->load($template)->render($vars), $this->config('tpl_replace_string'));
    }

    public function display($template, $vars, $configs)
    {
        return $this->parseTemplate($template, $vars, $configs);
    }
    public function getEnvironment()
    {
        return $this->environment;
    }
}